package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.AdminGoodsService;
import com.cskaoyan.market.util.MybatisUtils;
import com.cskaoyan.market.vo.CatAndBrandVo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author:yanzijun
 * @time:2024/06/18/14:54
 */
public class AdminGoodsServiceImpl implements AdminGoodsService {


    @Override
    public List<MarketGoods> list(String page, String limit, String sort, String order, String id, String goodsSn, String name) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if (StringUtils.isNotEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (StringUtils.isNotEmpty(goodsSn)) {
            criteria.andGoodsSnLike("%" + goodsSn + "%");
        }
        if (StringUtils.isNotEmpty(id)) {
            criteria.andIdEqualTo(Integer.valueOf(id));
        }
        marketGoodsExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketGoods> list = mapper.selectByExample(marketGoodsExample);
        session.close();
        return list;
    }


    @Override
    public Integer delete(MarketGoods marketGoods) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        int i = mapper.deleteByPrimaryKey(marketGoods.getId());
        session.commit();
        session.close();
        return i;
    }

    @Override
    public MarketGoods getMarketgood(int goodId) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoods marketGoods = mapper.selectByPrimaryKey(goodId);
        session.close();
        return marketGoods;
    }

    @Override
    public List<MarketGoodsAttribute> getMarketgoodAttributes(int goodId) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsAttributeMapper mapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodId);
        List<MarketGoodsAttribute> marketGoodsAttributeList = mapper.selectByExample(marketGoodsAttributeExample);
        session.close();
        return marketGoodsAttributeList;
    }

    @Override
    public List<MarketGoodsProduct> getProducts(int goodId) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsProductMapper mapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(goodId);
        List<MarketGoodsProduct> productList = mapper.selectByExample(marketGoodsProductExample);
        session.close();
        return productList;
    }

    @Override
    public List<MarketGoodsSpecification> getSpecification(int goodId) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsSpecificationMapper mapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodId);
        List<MarketGoodsSpecification> specificationList = mapper.selectByExample(marketGoodsSpecificationExample);
        session.close();
        return specificationList;
    }

    @Override
    public Map<String, Object> catAndBrand() {
        SqlSession session = MybatisUtils.getSession();
        MarketBrandMapper brandMapper = session.getMapper(MarketBrandMapper.class);
        MarketCategoryMapper cateMapper = session.getMapper(MarketCategoryMapper.class);
        List<MarketBrand> marketBrands = brandMapper.selectByExample(new MarketBrandExample());
        List<MarketCategory> marketCategories = cateMapper.selectByExample(new MarketCategoryExample());
        session.close();
        //brandList
        List<CatAndBrandVo> brandVos = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            brandVos.add(new CatAndBrandVo(marketBrand.getId(), marketBrand.getName(), null));
        }
        //categoryList
        List<CatAndBrandVo> catVos = new ArrayList<>();

        Map<Integer, List<MarketCategory>> cateMap = groupById(marketCategories);
        List<MarketCategory> l1Categories = cateMap.get(0);

        for (MarketCategory l1Category : l1Categories) {
            ArrayList<CatAndBrandVo> l2Categories = new ArrayList<>();
            catVos.add(new CatAndBrandVo(l1Category.getId(), l1Category.getName(), l2Categories));
            List<MarketCategory> marketCategoriesList = cateMap.get(l1Category.getId());
            if (marketCategoriesList == null) {
                continue;
            }
            for (MarketCategory marketCategory : marketCategoriesList) {
                l2Categories.add(new CatAndBrandVo(marketCategory.getId(), marketCategory.getName(), null));
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("brandList", brandVos);
        map.put("categoryList", catVos);
        return map;
    }

    @Override
    public int[] getCategoryIds(String id) {
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketCategoryMapper cateMapper = session.getMapper(MarketCategoryMapper.class);
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(Integer.valueOf(id));
        int categoryId = marketGoods.getCategoryId();
        MarketCategory marketCategory = cateMapper.selectByPrimaryKey(categoryId);
        int pid = marketCategory.getPid();
        return new int[]{pid, categoryId};
    }

    @Override
    public int update(MarketGoods goods, List<MarketGoodsAttribute> attributes, List<MarketGoodsProduct> products, List<MarketGoodsSpecification> specifications) {


        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        //如果商品编号为null,则报错
        if (StringUtils.isEmpty(goods.getGoodsSn())) {
            return 2;
        }
        //商品名字不能为空
        if (StringUtils.isEmpty(goods.getName())) {
            return 3;
        }
        goods.setUpdateTime(LocalDateTime.now());
        goodsMapper.updateByPrimaryKeySelective(goods);

        //对attribus进行数据处理
        //现将原来的数据删除
        //再重新插入attributes中的数据
        MarketGoodsAttributeExample example = new MarketGoodsAttributeExample();
        example.createCriteria().andGoodsIdEqualTo(goods.getId());
        attributeMapper.deleteByExample(example);

        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attribute.setUpdateTime(LocalDateTime.now());
            attributeMapper.insertSelective(attribute);
        }


        //对products进行处理

        for (MarketGoodsProduct product : products) {

            product.setUpdateTime(LocalDateTime.now());
            productMapper.updateByPrimaryKeySelective(product);

        }
        //对specifications进行处理
        for (MarketGoodsSpecification specification : specifications) {

            specification.setUpdateTime(LocalDateTime.now());
            specificationMapper.updateByPrimaryKeySelective(specification);

        }
        session.commit();
        session.close();
        return 1;
    }

    @Override
    public void create(MarketGoods goods, List<MarketGoodsSpecification> specifications, List<MarketGoodsAttribute> attributes, List<MarketGoodsProduct> products) {
        BigDecimal retailPrice = products.get(0).getPrice();
        for (int i = 0; i < products.size(); i++) {
            MarketGoodsProduct product = products.get(i);
            //遍历，如果出现了一个更小的价格，那么把更小的价格赋值给retailPrice
            // -1 小于 0 等于 1  大于
            if (product.getPrice().compareTo(retailPrice) == -1) {
                retailPrice = product.getPrice();
            }
        }

        goods.setRetailPrice(retailPrice);
        goods.setAddTime(LocalDateTime.now());
        goods.setUpdateTime(LocalDateTime.now());
        goods.setDeleted(false);
        SqlSession session = MybatisUtils.getSession();
        MarketGoodsMapper marketGoodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        // insert into (xx,xx) values (xx,xx)---除了这两列之外的其他列，如果有默认值，则会赋值默认值
        // insert into xxx values (xx,xx,xx,xx,xx,xx)---给全部的列赋值，但是实体类里面有很多的null，所以这一列会被赋值null
        try {
            marketGoodsMapper.insert(goods);
            Integer goodsId = goods.getId();
            //关于下面这三个插入，大家可以自定义一个插入方法，使用foreach标签来进行
            for (MarketGoodsSpecification sp : specifications) {
                sp.setGoodsId(goodsId);
                sp.setAddTime(LocalDateTime.now());
                sp.setUpdateTime(LocalDateTime.now());
                specificationMapper.insert(sp);
            }
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goodsId);
                attribute.setAddTime(LocalDateTime.now());
                attribute.setUpdateTime(LocalDateTime.now());
                attributeMapper.insert(attribute);
            }

            for (MarketGoodsProduct product : products) {
                product.setAddTime(LocalDateTime.now());
                product.setUpdateTime(LocalDateTime.now());
                product.setGoodsId(goodsId);
                productMapper.insert(product);
            }
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    private Map<Integer, List<MarketCategory>> groupById(List<MarketCategory> marketCategories) {
        HashMap<Integer, List<MarketCategory>> integerListHashMap = new HashMap<>();
        for (MarketCategory marketCategory : marketCategories) {
            Integer pid = marketCategory.getPid();
            List<MarketCategory> list = integerListHashMap.get(pid);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(marketCategory);
            integerListHashMap.put(pid, list);
        }
        return integerListHashMap;
    }
}
